package com.jmp.sms;

import lombok.extern.slf4j.Slf4j;
import one.stand.code.RedisCode;
import one.stand.util.AssertUtil;
import one.stand.util.RandomUtil;
import one.stand.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class CaptchaServiceImpl implements CaptchaService {
    private RedisUtil redisUtil;
    private SmsClient smsClient;

    public CaptchaServiceImpl(RedisUtil redisUtil, SmsClient smsClient) {
        this.redisUtil = redisUtil;
        this.smsClient = smsClient;
    }

    @Override
//    @Async("asyncServiceExecutor")
    public void send(String phone, Integer type, String ip, int length) {
        AssertUtil.isFalse(redisUtil.hasKey(RedisCode.getSmsLockKey(phone)), "操作频繁");

        String smsCode = RandomUtil.generateNumberString(length > 0 ? length : 6);
        redisUtil.set(RedisCode.getSmsKey(phone, type), smsCode, 30, TimeUnit.MINUTES);
        redisUtil.set(RedisCode.getSmsLockKey(phone), ip, 60, TimeUnit.SECONDS);

        SmsClientCodeRequest smsClientCodeRequest = SmsClientCodeRequest.builder()
                .phone(phone)
                .type(type)
                .code(smsCode)
                .build();
        smsClient.sendSmsCode(smsClientCodeRequest);
    }

    @Override
    public boolean check(String phone, Integer type, String captcha) {
        String key = RedisCode.getSmsKey(phone, type);
        String redisSmsCode = redisUtil.get(key);
        log.debug("删除用户验证码缓存");
        redisUtil.remove(key);
        redisUtil.remove(RedisCode.getSmsLockKey(phone));
        boolean isTrue = StringUtils.isNoneBlank(redisSmsCode) && redisSmsCode.equals(captcha);
        if (!isTrue) {
            log.warn("captcha error: redis is [{}], but user set [{}]", redisSmsCode, captcha);
        }
        return isTrue;
    }

    @Override
    @Async("asyncServiceExecutor")
    public void sendBatch(List<String> phones, Integer type, String params) {
        smsClient.sendBatchSms(phones, type, params);
    }
}
